package cc.shacocloud.luanniao.core.utils

import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.PropertyAccessor
import com.fasterxml.jackson.core.JsonParser.Feature
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

/**
 * Json 工具对象
 *
 * @author 思追(shaco)
 */
object Json {

    const val CLASS_KEY: String = "@type"

    /**
     * 带类型的 [ObjectMapper]
     */
    val typeMapper = Jackson2ObjectMapperBuilder.json()
        .postConfigurer {
            it.configure(Feature.ALLOW_COMMENTS, true)
            it.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

            // 设置类型字段
            it.activateDefaultTypingAsProperty(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL_AND_ENUMS,
                CLASS_KEY
            )
            it.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
        }
        .build<ObjectMapper>()

    /**
     * 普通的 [ObjectMapper]
     */
    val mapper = Jackson2ObjectMapperBuilder.json()
        .postConfigurer {
            it.configure(Feature.ALLOW_COMMENTS, true)
            it.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        }
        .build<ObjectMapper>()

}